package cn.funeralobjects.common.web.controller;

import cn.funeralobjects.common.service.CodeService;
import cn.funeralobjects.util.ReactorUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import reactor.core.publisher.Mono;

/**
 * 带编码的Controller
 *
 * @author FuneralObjects
 * Create date: 2020/4/28 10:11 AM
 */
public interface RestCodeController<VO, Entity, ID> extends ModelMapperController<Entity, VO>, IdController<ID> {

    /**
     * 编码业务
     *
     * @return 编码业务对象
     */
    CodeService<Entity, ID> codeService();

    /**
     * 通过编码获取对象
     *
     * @param code 编码
     * @return vo
     */
    @GetMapping("/code-{code}")
    default Mono<VO> findByCode(@PathVariable String code) {
        return Mono.just(code)
                .filter(codeService()::isValid)
                .map(codeService()::findByCode)
                .flatMap(ReactorUtils::getOrEmpty)
                .map(this::toVo);
    }

    /**
     * 通过编码获取id
     *
     * @param code 编码
     * @return id
     */
    @GetMapping("/code-{code}/id")
    default Mono<ID> getId(@PathVariable String code) {
        return Mono.just(code)
                .filter(codeService()::isValid)
                .map(codeService()::getId)
                .flatMap(ReactorUtils::getOrEmpty);
    }

    /**
     * 通过id获取编码
     *
     * @param id id
     * @return 编码
     */
    @GetMapping("/{id}/code")
    default Mono<String> getCode(@PathVariable ID id) {
        return Mono.just(id)
                .filter(this::isValid)
                .map(codeService()::getCode)
                .flatMap(ReactorUtils::getOrEmpty);
    }

}
